﻿using System;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WorkFlowWindowsForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            Console.WriteLine("主线程编号="+Thread.CurrentThread.ManagedThreadId.ToString());
            WorkflowApplication application = new WorkflowApplication(new Activity1(),new Dictionary<string, object>()
            {
                { "TempDateTime",DateTime.Now }
            });

            AutoResetEvent synEvent = new AutoResetEvent(false);
            
            application.Completed = delegate(WorkflowApplicationCompletedEventArgs args)
            {
                synEvent.Set();
                Console.WriteLine("工作流完成");
            };
            application.Idle = delegate(WorkflowApplicationIdleEventArgs args)
            {
                synEvent.Set();
                Console.WriteLine("工作流空闲");
            };
            application.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs args)
            {
                synEvent.Set();
                Console.WriteLine("工作流持久化");
                return PersistableIdleAction.Unload;
            };
            application.Unloaded = delegate(WorkflowApplicationEventArgs args)
            {
                synEvent.Set();
                Console.WriteLine("工作流卸载");
            };
            application.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs args)
            {
                synEvent.Set();
                Console.WriteLine("工作流异常");
                return UnhandledExceptionAction.Abort;
            };

            application.Run();//开启新的线程执行工作流
            synEvent.WaitOne();//主线程停止了
            Console.WriteLine("主线程继续执行");
        }
    }
}
